package org.jks.sms;

import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.Message.MessageEncodings;
import org.smslib.modem.SerialModemGateway;
/**
 * 短信类
 * @author turan
 *
 */
public class Sms {
	public static int SUCCESS = 0;
	public static int ERRCODE_PARAMS = 1;
	public static int ERRCODE_START_FAIL = 2;
	public static int ERRCODE_STOP_FAIL = 3;
	public static int ERRCODE_SEND_FAIL = 4;
	public static int ERRCODE_NOT_FOUND_SERVER = 5;
	
	public static Service srv = null;
	public static OutboundNotification outboundNotification = null;
	public static InboundNotification inboundNotification = null;
	/**
	 * 获得一个新的短信服务
	 * @return 错误码
	 */
	public static int init(String comPort, int baudRate){
		if(srv == null){
			srv = new Service();
			outboundNotification = new OutboundNotification();
			inboundNotification = new InboundNotification(srv);
		}
		else{
			return SUCCESS;
		}
		if(comPort == null || comPort.length() == 0){
			return ERRCODE_PARAMS;
		}
		SerialModemGateway gateway = new SerialModemGateway("jks", comPort, baudRate, "wavecom", "17254");
		gateway.setInbound(true);
		gateway.setOutbound(true);
		gateway.setSimPin("0000");
		gateway.setOutboundNotification(outboundNotification);
		gateway.setInboundNotification(inboundNotification);
		srv.addGateway(gateway);
		return start();
	}
	
	/**
	 * 启动服务
	 * @return 返回错误码
	 */
	public static int start(){
		if(srv == null){
			return ERRCODE_NOT_FOUND_SERVER;
		}
		try {
			srv.startService();
		} catch (Exception e) {
			return ERRCODE_START_FAIL;
		} 
		return SUCCESS;
	}
	
	/**
	 * 停止服务
	 * @return 返回错误码
	 */
	public static int stop(){
		if(srv == null){
			return ERRCODE_NOT_FOUND_SERVER;
		}
		try {
			srv.stopService();
		} catch (Exception e) {
			e.printStackTrace();
			return ERRCODE_STOP_FAIL;
		} 
		return SUCCESS;
	}
	
	/**
	 * 重启服务
	 * @param comPort 串口号
	 * @param baudRate 波特率
	 * @return 返回错误码
	 */
	public static int restart(String comPort, int baudRate){
		if(stop() == SUCCESS){
			return init(comPort, baudRate);
		}
		return -1;
	}
	
	/**
	 * 发送短息
	 * @param telephone 电话号码
	 * @param text 内容
	 * @return 返回错误码
	 */
	public static int sendMessage(String telephone, String text){
		OutboundMessage outmsg = new OutboundMessage(telephone, text);
		outmsg.setEncoding(MessageEncodings.ENCUCS2);
		try {
			srv.sendMessage(outmsg);
		} catch (Exception e) {
			e.printStackTrace();
			return ERRCODE_SEND_FAIL;
		} 
		return SUCCESS;
	}
}
